const path = require("path");
const semver = require("semver");
const colors = require("colors/safe");
const rootCheck = require("root-check");
const userHome = require("user-home");
const pathExists = require("path-exists").sync;
const dotenv = require("dotenv");

const log = require("@azir-cli/log");
const { getNpmInfo } = require("@azir-cli/get-npm-info");
const pkg = require("../package.json");
const { DEFAULT_CLI_HOME } = require("./constant");

module.exports = prepare;

async function prepare() {
  // 前置检查
  checkPkgVersion();
  checkRoot();
  checkUserHome();
  checkENV();
  await checkVersion();
}

/**
 * 检查环境变量
 */
function checkENV() {
  const dotenvPath = path.resolve(userHome, ".env");
  if (pathExists(dotenvPath)) {
    dotenv.config({ path: dotenvPath });
  }
  createDefaultConfig();
  {
    log.debug("环境变量", process.env);
  }
}
function createDefaultConfig() {
  const config = {
    home: userHome,
    cliHome: path.join(
      userHome,
      process.env.AZIR_CLI_HOME ? process.env.AZIR_CLI_HOME : DEFAULT_CLI_HOME
    ),
  };
  process.env.AZIR_CLI_HOME_PATH = config.cliHome;
}

/**
 * 检查用户主目录
 */
function checkUserHome() {
  if (!userHome || !pathExists(userHome)) {
    throw new Error(colors.red(`用户主目录 ${userHome} 不存在。`));
  }
}
/**
 * 检查Root启动
 */
function checkRoot() {
  rootCheck();
}

/**
 * 检查版本号
 */
function checkPkgVersion() {
  log.info("azir-cli version", pkg.version);
}

/**
 * 检查版本
 */
async function checkVersion() {
  //1. 获取当前版本号
  const currentVersion = pkg.version;
  const pkgName = pkg.name;
  //2. 调用npm API，获取所有的版本号
  const { lastVersion } = await getNpmInfo(pkgName);
  //3. 获取最新的版本号，提示用户更新到改版本
  if (lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn(`最新版本: ${lastVersion}\n更新命令: npm i -g ${pkgName}`);
  }
}
